<template>
  <div ref="plyrContainer" class="w-screen h-screen pr-4 bg-black relative">
    <VideoInfos :video="props.video" class="absolute bottom-8 left-8 z-10" />

    <div class="w-full h-full mx-5 flex items-stretch justify-center pr-28">
      <video ref="videoElement" :src="video.play_url" :poster="video.cover_url" webkit-playsinline playsinline
             x5-playsinline :title="video.title" x5-video-player-type="h5" x5-video-player-fullscreen="true" preload="auto"
             loop muted v-if="props.video.type === 0" />

      <Carousel v-else>
        <div v-for="(image, index) in imageList" :key="index" :style="{ backgroundSize: 'cover', backgroundImage: `url('${image.url}')` }">
          <Image :src="'http://localhost:8080' + image.url" width="100%" height="100%" />
        </div>
      </Carousel>
    </div>

    <VideoActions :video="video" class="fixed top-1/2 right-[25px] transform -translate-y-1/2 z-10" />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import Plyr from 'plyr'
import 'plyr/dist/plyr.css'
import { useIntersectionObserver } from '@vueuse/core'
import { Carousel, Image  } from '@kousum/semi-ui-vue'
import type { Video, ImageResponse, WorkImage } from '@/services/video/video.types'
import services from '@/services'
import VideoInfos from './VideoInfos.vue'
import VideoActions from '@/components/VideoActions.vue'

const props = defineProps<{
  video: Video
}>()

const plyrContainer = ref<HTMLDivElement>()
const videoElement = ref<HTMLVideoElement>()
const isPlaying = ref(false)
const imageList = ref<WorkImage[]>([])
let player: Plyr | null = null

// 初始化 Plyr 播放器
onMounted(() => {
  if(props.video.type === 0) {
    initPlayer()
  } else if(props.video.type === 1) {
    initCarousel()
  }
});

// 初始化播放器
function initPlayer() {
  console.log("当前 Video ", props.video)
  console.log("开始播放url：", props.video.play_url)

  if (videoElement.value) {
    player = new Plyr(videoElement.value, {
      controls: ['play', 'progress', 'current-time', 'mute', 'volume', 'fullscreen'], // 显示控制条
      autoplay: false,
      loop: { active: true }
    })

    console.log('Plyr player initialized:', player) // 检查 player 是否正确初始化

    // 监听播放事件
    player.on('play', () => {
      isPlaying.value = true
    })

    // 监听暂停事件
    player.on('pause', () => {
      isPlaying.value = false
    })

    // 监听结束事件
    player.on('ended', () => {
      player?.play()
    })
  } else {
    console.error('Video element is not found') // 检查 videoElement 是否未绑定
  }
}

// 初始化轮播图
async function initCarousel() {
  try {
    const response: ImageResponse = await services.video.getVideoImages(String(props.video.id));
    imageList.value = response.list
  } catch (error) {

  }
}

// 销毁 Plyr 播放器
onUnmounted(() => {
  if (player) {
    player.destroy()
  }
})

// 使用 IntersectionObserver 监听视频是否在视口中
const { stop } = useIntersectionObserver(
  plyrContainer,
  ([{ isIntersecting }]) => {
    if (isIntersecting) {
      player?.play()
    } else {
      player?.pause()
    }
  },
  { threshold: 0.5 }
)

onUnmounted(() => {
  stop()
})
</script>
